package com.test.com.bluetoothchatandroid.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.orhanobut.logger.Logger;
import com.test.com.bluetoothchatandroid.R;
import com.test.com.bluetoothchatandroid.adapter.ListAdapter;
import com.test.com.bluetoothchatandroid.base.BaseActivity;
import com.test.com.bluetoothchatandroid.callback.BluetoothScanCallback;
import com.test.com.bluetoothchatandroid.callback.PairedCallback;
import com.test.com.bluetoothchatandroid.receiver.PairedBroadcastReceiver;
import com.test.com.bluetoothchatandroid.receiver.ScanBluetoothBroadcastReceiver;
import com.test.com.bluetoothchatandroid.utils.BluetoothUtil;
import com.test.com.bluetoothchatandroid.widgets.decorator.EasyBorderDividerItemDecoration;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author saviorT
 */
public class AddFriendActivity extends BaseActivity implements XRecyclerView.LoadingListener{

	@BindView(R.id.center_title)
	TextView centerTitle;
	@BindView(R.id.toolbar)
	Toolbar toolbar;
	@BindView(R.id.xRecyclerView)
	XRecyclerView xRecyclerView;


	private ListAdapter mAdapter;
	private ScanBluetoothBroadcastReceiver mScanBroadcastReceiver;
	private PairedBroadcastReceiver mPairedReceiver;
	private List<BluetoothDevice> mBluetoothDevices = new ArrayList<>();
	private Map<String, BluetoothDevice> mDeviceMap = new HashMap<>();


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_friend);

		ButterKnife.bind(this);

		initView();
	}

	private final BluetoothScanCallback<BluetoothDevice> scanCallback = new BluetoothScanCallback<BluetoothDevice>() {
		@Override
		public void discoverDevice(BluetoothDevice bluetoothDevice) {
			System.out.println("searching bluetooth device");
			if (!mDeviceMap.containsKey(bluetoothDevice.getAddress())){
				// 放进map用作比较
				mDeviceMap.put(bluetoothDevice.getAddress(),bluetoothDevice);
				mBluetoothDevices.add(bluetoothDevice);
				mAdapter.setList(mBluetoothDevices);
				mAdapter.notifyDataSetChanged();
			}
		}

		@Override
		public void scanTimeout() {
			System.out.println("Scan TIMEOUT!");
		}

		@Override
		public void scanFinish(List<BluetoothDevice> list) {
			System.out.println("Scan FINISH!");
			hideLoading();
			showToast("-=扫描设备完成=-");
		}
	};
	private final PairedCallback pairedCallback = new PairedCallback() {

		@Override
		public void unBonded() {
			hideLoading();
			System.out.println("unBonded.............");
		}

		@Override
		public void bonding() {
			System.out.println("bonding..............");
		}

		@Override
		public void bonded() {
			hideLoading();
			showToast("添加好友成功");
		}

		@Override
		public void bondFailed() {
			hideLoading();
			showToast("添加好友失败");
		}

	};


	private void initView() {
		mBluetoothDevices = new ArrayList<>();
		mDeviceMap = new HashMap<>();
//		mPairedReceiver = new PairedBroadcastReceiver(this);
//		mScanBroadcastReceiver = new ScanBluetoothBroadcastReceiver(this);
		centerTitle.setText("添加好友");
		setToolbar(toolbar);
		initRecyclerView();
		initData();
		System.out.println("method step initVIEW");
	}

	private void initRecyclerView() {
		xRecyclerView.setLoadingListener(this);
		mAdapter = new ListAdapter(this);
		LinearLayoutManager manager = new LinearLayoutManager(this);
		xRecyclerView.setLayoutManager(manager);
		EasyBorderDividerItemDecoration itemDecoration = new EasyBorderDividerItemDecoration(getResources().getDimensionPixelOffset(R.dimen.data_border_divider_height),0);
		xRecyclerView.addItemDecoration(itemDecoration);
		xRecyclerView.setAdapter(mAdapter);
	}

	private void initData() {
		beginDiscover();
		mAdapter.setOnItemClickListener((convertView, position) -> {
			if (mBluetoothDevices.get(position).getBondState() != BluetoothDevice.BOND_BONDED){
				startPair();//
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
					mBluetoothDevices.get(position).createBond();
				}else {
					// 利用反射方法调用BluetoothDevice.createBond(BluetoothDevice remoteDevice)；
					Method createBondMethod = null;
					try {
						createBondMethod = BluetoothDevice.class.getMethod("createBond");
						createBondMethod.invoke(mBluetoothDevices.get(position));
					}catch (NoSuchMethodException e){
						e.printStackTrace();
					}catch (IllegalAccessException e){
						e.printStackTrace();
					}catch (InvocationTargetException e){
						e.printStackTrace();
					}
					showLoading("与好友配对中...");
				}
			}else {
				showToast("已经是你的好友了，不能重复添加！");
			}
		});
	}

	private void startPair() {
		showLoading("开始配对...");
		if (mPairedReceiver == null){
			mPairedReceiver = new PairedBroadcastReceiver(pairedCallback);
		}
		// register bluetooth pair scanner
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
		registerReceiver(mPairedReceiver,intentFilter);
	}

	private void beginDiscover() {
		showLoading("正在搜索设备....");
		System.out.println("method step beginDiscover...");
		if (mScanBroadcastReceiver == null){
			mScanBroadcastReceiver = new ScanBluetoothBroadcastReceiver(scanCallback);
		}
		// register bluetooth scanner
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
		intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		registerReceiver(mScanBroadcastReceiver,intentFilter);
		BluetoothUtil.enableBluetooth((Activity) mContext,1);
	}

	// use override onActivityResult to get data
	@Override
	public void onActivityResult(int requestCode,int resultCode, Intent data) {
		if (requestCode == 1){
			if (resultCode == RESULT_OK){
				BluetoothAdapter.getDefaultAdapter().startDiscovery();
				Logger.d("开始搜索设备...");
			}else {
				finish();
			}
		}
		super.onActivityResult(requestCode,resultCode,data);
	}


	@Override
	protected void onDestroy() {
		BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
		if (mScanBroadcastReceiver != null){
			unregisterReceiver(mScanBroadcastReceiver);
			mScanBroadcastReceiver = null;
		}
		if (mPairedReceiver != null){
			unregisterReceiver(mPairedReceiver);
			mPairedReceiver = null;
		}
		super.onDestroy();
	}


	@Override
	public void onRefresh() {
		showToast("数据已经是最新的了");
		xRecyclerView.refreshComplete();
	}

	@Override
	public void onLoadMore() {
		showToast("没有更多设备");
		xRecyclerView.loadMoreComplete();
	}
}
